﻿using System;
using System.Web.Mvc;
using AutoMapper;
using Portal.Logic.Providers;
using Portal.Model;
using Portal.Presentation.Models;
using Portal.Presentation.Services;
using Portal.Presentation.Providers;
using Portal.Presentation.Converters;
using Portal.Logic.Services;

namespace Portal.Presentation.Controllers
{
	[CustomHandleError(View = "Error")]
	public class UserInfoController : ControllerBase
	{
		#region Fields
		private readonly IUserInfoService _service;
		private readonly IUserViewModelConverter _converter;
		#endregion

		#region .ctor
		/// <summary>
		/// Initializes a new instance of the <see cref="UserInfoController" /> class.
		/// </summary>
		/// <param name="session">The session.</param>
		/// <exception cref="System.ArgumentNullException">session</exception>
		public UserInfoController(ISecurityProvider security, IUserInfoService service, ISessionService session, IUserViewModelConverter converter)
			: base(security, session)
		{
			if (converter == null)
			{
				throw new ArgumentNullException("converter");
			}
			if (service == null)
			{
				throw new ArgumentNullException("service");
			}
			_converter = converter;
			_service = service;
		}
		#endregion

		#region Methods
		//
		// GET: /User/
		public ActionResult Preview()
		{
			var user = SecurityProvider.GetUser(GetLogon());
			var userInfo = _service.GetBy(user);
			var model = _converter.ToModel(userInfo);
			if (model != null)
			{
				return View(model);
			}
			return RedirectToAction("General", "Error");
		}

		//
		// GET: /User/Edit/
		public ActionResult Edit()
		{
			var user = GetCurrentUser();
			var userInfo = _service.GetBy(user);
			var model = userInfo.MapNew<IUserInfo, UserInfoDataModel>();
			return View(model);
		}

		//
		// POST: /User/Edit/
		[HttpPost]
		public ActionResult Edit(UserInfoDataModel model)
		{
			try
			{
				if (ModelState.IsValid)
				{
					var user = GetCurrentUser();
					var userInfo = _converter.ToUserInfo(model, user);
					_service.Save(userInfo);
					return RedirectToAction("Preview");
				}
			}
			catch (Exception ex)
			{
				ViewBag.Error = ex.Message;
			}
			return View();
		}

		#endregion
	}
}